<?php

namespace think\wework\Abstracts;

use think\facade\Cache;
use think\wework\Http\ClientFactory;

abstract class WeworkApiWithCache extends WeworkApi
{
    public function __construct()
    {
        parent::__construct();
        $this->httpClient = ClientFactory::create();
    }
    /**
     * @return string
     */
    abstract protected function getCacheKey(): string;

    /**
     * @return mixed
     */
    abstract protected function getFromServer();

    /**
     * @param bool $refresh
     * @return mixed
     */
    public function get(bool $refresh = false)
    {
        $key = $this->getCacheKey();

        $value = Cache::get($key);

        if ($refresh || !$value) {
            $value = $this->getFromServer();
            Cache::set($key, $value, 7100);
        }

        return $value;
    }
}